package com.clock.service.impl;

import com.clock.common.constant.TagKey;
import com.clock.domain.entity.Tag;
import com.clock.domain.entity.TagModule;
import com.clock.domain.vo.TagVo;
import com.clock.mapper.TagMapper;
import com.clock.mapper.TagModuleMapper;
import com.clock.service.TagService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


@Service
public class TagServiceImpl implements TagService {

    @Resource
    TagMapper tagMapper;

    @Resource
    TagModuleMapper tagModuleMapper;

    @Resource
    StringRedisTemplate stringRedisTemplate;



   /* @Override
    下面是set版本的方案  存在问题是，不方便标签id的存储
    public List<TagVo> getAllTag() {

        List<TagVo> tagVoList = getAllTagByCache();
        if(tagVoList != null){
            return tagVoList;
        }else{
            List<TagVo> allTagByData = getAllTagByData();
            return allTagByData;
        }

    }

    //查询tagModule 和 tag的缓存
    private List<TagVo> getAllTagByCache(){
        //最终是查所有标签
        List<TagVo> tagVoList = new ArrayList<>();

        //先查缓存有没有东西
        Set<String> members = stringRedisTemplate.opsForSet().
                members(TagKey.TAG_PREFIX + ":" + TagKey.TAG_MODULE_KEY);
        if(!members.isEmpty()){
            for (String member : members) {
                String[] split = member.split("-");
                Set<String> tagsByModuleName = stringRedisTemplate.opsForSet().
                        members(TagKey.TAG_PREFIX + ":" + TagKey.TAG_KEY + ":" + split[1]);
                List<Tag> tagList = new ArrayList<>();
                if(!tagsByModuleName.isEmpty()){
                    for (String tags : tagsByModuleName) {
                        Tag tag = new Tag();
                        tag.setTagContent(tags);
                        tagList.add(tag);
                    }
                    TagVo tagVo = new TagVo(Integer.valueOf(split[0]),split[1],tagList);
                    tagVoList.add(tagVo);
                }else{
                    return null;
                }
            }
            return tagVoList;
        }else{
            return null;
        }
    }

    //在数据库中查询tagModule 和 tag
    private List<TagVo> getAllTagByData(){
        //最终是查所有标签
        List<TagVo> tagVoList = new ArrayList<>();

        //查询tag有哪些模块，把模块名以set形式存储
        List<TagModule> tagModules = tagModuleMapper.queryAll();
        if(tagModules == null){
            return null;
        }

        for (TagModule tagModule : tagModules) {
            stringRedisTemplate.opsForSet().add(TagKey.TAG_PREFIX + ":" + TagKey.TAG_MODULE_KEY,
                    tagModule.getTagModuleId()+"-"+tagModule.getTagModuleName());
        }


        for (TagModule tagModule : tagModules) {
            List<Tag> tags = tagMapper.queryAllByTagModuleIdTags(tagModule.getTagModuleId());
            //存去返回值里
            if(!tags.isEmpty()){
                for (Tag tag : tags) {
                    stringRedisTemplate.opsForSet().add(TagKey.TAG_PREFIX +":"+TagKey.TAG_KEY +":"+tagModule.getTagModuleName(),
                            tag.getTagContent());
                }
                TagVo tagVo = new TagVo(tagModule.getTagModuleId(),tagModule.getTagModuleName(),tags);
                tagVoList.add(tagVo);
            }
        }
        return tagVoList;
    }

    @Override
    public String insertTag(Tag tag) {
        String tagContent = tag.getTagContent();

        Set<String> members = stringRedisTemplate.opsForSet().
                members(TagKey.TAG_PREFIX + ":" + TagKey.TAG_MODULE_KEY);
        String tagModuleName = new String();
        for (String member : members) {
            String[] split = member.split("-");
            if(split[0].equals(String.valueOf(tag.getTagModuleId()))){
                tagModuleName = split[1];
            }
        }

        Boolean aBoolean = stringRedisTemplate.opsForSet().isMember
                (TagKey.TAG_PREFIX + ":" + TagKey.TAG_KEY + ":" + tagModuleName, tagContent);
        if(aBoolean){
            return "标签已存在";
        }

        int insert = 0;
        try {
            insert = tagMapper.insert(tag);
        } catch (Exception e) {
            return "新建标签出现异常";
        }
        if(insert <= 0){
            return "新建标签失败";
        }


        stringRedisTemplate.opsForSet().add(TagKey.TAG_PREFIX +":"+TagKey.TAG_KEY +":"+tagModuleName,
                tagContent);

        return "新建标签成功";
    }

    @Override
    public boolean deleteTag(Tag tag) {
        String tagContent = tag.getTagContent();

        Set<String> members = stringRedisTemplate.opsForSet().
                members(TagKey.TAG_PREFIX + ":" + TagKey.TAG_MODULE_KEY);
        String tagModuleName = new String();
        for (String member : members) {
            String[] split = member.split("-");
            if(split[0].equals(String.valueOf(tag.getTagModuleId()))){
                tagModuleName = split[1];
            }
        }

        Boolean aBoolean = stringRedisTemplate.opsForSet().isMember
                (TagKey.TAG_PREFIX + ":" + TagKey.TAG_KEY + ":" + tagModuleName, tagContent);
        if(!aBoolean){
            return false;
        }

        int delByTagContentAndTagModuleIdInt = tagMapper.delByTagContentAndTagModuleIdInt(tag.getTagModuleId(), tag.getTagContent());
        if(delByTagContentAndTagModuleIdInt <= 0){
            return false;
        }
        return true;
    }
*/
    //下面是hashMap 存储版本 被淘汰  现在又用回来了

    public List<TagVo> getAllTag() {

        List<TagVo> tagVoList = getAllTagByCache();
        if(tagVoList != null){
            return tagVoList;
        }else{
            List<TagVo> allTagByData = getAllTagByData();
            return allTagByData;
        }

    }


    //查询tagModule 和 tag的缓存
    private List<TagVo> getAllTagByCache(){
        //最终是查所有标签
        List<TagVo> tagVoList = new ArrayList<>();

        //先查缓存有没有东西
        Map<Object, Object> tagModuleEntries = stringRedisTemplate.opsForHash().
                entries(TagKey.TAG_PREFIX + ":" + TagKey.TAG_MODULE_KEY);
        if(!tagModuleEntries.isEmpty()){
            for (Map.Entry<Object, Object> entry : tagModuleEntries.entrySet()) {
                Map<Object, Object> tagEntries = stringRedisTemplate.opsForHash().
                        entries(TagKey.TAG_PREFIX + ":" + TagKey.TAG_KEY + ":" + (String)entry.getValue());
                List<Tag> tagList = new ArrayList<>();
                if(!tagEntries.isEmpty()){
                    for (Map.Entry<Object, Object> tagEntry : tagEntries.entrySet()) {
                        Tag tag = new Tag();
                        tag.setTagId(Long.valueOf((String)tagEntry.getKey()));
                        tag.setTagContent((String)tagEntry.getValue());
                        tagList.add(tag);
                    }
                    TagVo tagVo = new TagVo(Integer.valueOf((String)entry.getKey()),(String)entry.getValue(),tagList);
                    tagVoList.add(tagVo);
                }else{
                    return null;
                }
            }
            return tagVoList;
        }else{
            return null;
        }
    }

    //在数据库中查询tagModule 和 tag
    private List<TagVo> getAllTagByData(){
        //最终是查所有标签
        List<TagVo> tagVoList = new ArrayList<>();

        //查询tag有哪些模块，把模块名以hashMap形式存储
        List<TagModule> tagModules = tagModuleMapper.queryAll();
        if(tagModules == null){
            return null;
        }
        Map map = new HashMap<String,String>();
        for (TagModule tagModule : tagModules) {
            map.put(tagModule.getTagModuleId().toString(),tagModule.getTagModuleName());
        }
        stringRedisTemplate.opsForHash().putAll(TagKey.TAG_PREFIX + ":" + TagKey.TAG_MODULE_KEY,map);
        //以map形式存tag   键名：TagKey.TAG_PREFIX+"."+TagKey.tagKey+"."+tagModuleName
        for (TagModule tagModule : tagModules) {
            //获取每一个标签模块的所有的标签
            List<Tag> tags = tagMapper.queryAllByTagModuleIdTags(tagModule.getTagModuleId());
            //存去返回值里
            TagVo tagVo = new TagVo(tagModule.getTagModuleId(),tagModule.getTagModuleName(),tags);
            tagVoList.add(tagVo);

            Map tagMap = new HashMap<String,String>();
            for (Tag tag : tags) {
                tagMap.put(tag.getTagId().toString(),tag.getTagContent());
            }
            //将这个模块的所有tag存起来
            stringRedisTemplate.opsForHash().putAll(
                    TagKey.TAG_PREFIX+":"+TagKey.TAG_KEY+":"+tagModule.getTagModuleName(),tagMap);
        }

        return tagVoList;
    }

    //不可以带-号  我用了-号做分割
    @Override
    public boolean insertTag(Tag tag) {
        String tagContent = tag.getTagContent();

        Map<Object, Object> entries = stringRedisTemplate
                .opsForHash().entries(TagKey.TAG_PREFIX + ":" + TagKey.TAG_MODULE_KEY);
        String moduleName = (String)entries.get(tag.getTagModuleId().toString());
        if(moduleName == null){
            return false;
        }

        List<Object> values = stringRedisTemplate
                .opsForHash().values(TagKey.TAG_PREFIX + ":" + TagKey.TAG_KEY + ":" + moduleName);
        if(!values.isEmpty()&&values.contains(tagContent)){
            return false;
        }

        int insert = tagMapper.insert(tag);
        if(insert<=0){
            return false;
        }

        Tag queryByTagContent = tagMapper.queryByTagContent(tagContent);

        stringRedisTemplate
                .opsForHash().put(TagKey.TAG_PREFIX+":"+TagKey.TAG_KEY+":"+moduleName,
                        queryByTagContent.getTagId().toString(),queryByTagContent.getTagContent());

        return true;

        /*int insert = tagMapper.insert(tag);
        if(insert >= 1){
            Map<Object, Object> entries = stringRedisTemplate.opsForHash().
                    entries(TagKey.TAG_PREFIX + ":" + TagKey.TAG_MODULE_KEY);
            if(entries.isEmpty()){
                return true;
            }
            String tagModuleName = (String)entries.get(tag.getTagModuleId());
            Map<Object, Object> tagMap = stringRedisTemplate.opsForHash().
                    entries(TagKey.TAG_PREFIX + ":" + TagKey.TAG_KEY + ":" + tagModuleName);

            if(tagMap.containsValue(tag.getTagContent())){
                return false;
            }else{
                tagMap.put(TagKey.TAG_PREFIX + ":" + TagKey.TAG_KEY + ":" + tagModuleName,tag.getTagContent());
            }
        }else{
            return false;
        }
        return true;*/
    }

    @Override
    public boolean deleteTag(Tag tag) {
        int deleteById = tagMapper.deleteById(tag);
        if(deleteById >= 1){
            Map<Object, Object> entries = stringRedisTemplate.opsForHash().
                    entries(TagKey.TAG_PREFIX + ":" + TagKey.TAG_MODULE_KEY);
            if(entries.isEmpty()){
                return true;
            }
            String tagModuleName = (String)entries.get(String.valueOf(tag.getTagModuleId()));
            Long delete = stringRedisTemplate.opsForHash().
                    delete(TagKey.TAG_PREFIX + ":" + TagKey.TAG_KEY + ":" + tagModuleName, String.valueOf(tag.getTagId().longValue()));
            return true;
        }
        return false;
    }
}
